package com.cf.user.permission.service;

import com.cf.crud.service.AbsBaseService;
import com.cf.id.SnowflakeId;
import com.cf.user.permission.dao.SystemRoleDao;
import com.cf.user.permission.dao.UserWithRoleDao;
import com.cf.user.permission.model.SystemRole;
import com.cf.user.permission.model.UserWithRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * game-server-SysRoleService
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/5/31 上午 11:17
 */

@Slf4j
public class SystemRoleServiceImpl extends AbsBaseService<SystemRole, SystemRoleDao> implements SystemRoleService {

    @Autowired
    private SnowflakeId id;

    @Autowired
    private UserWithRoleDao userWithRoleDao;

    @Override
    public Class getTargetClass() {
        return SystemRole.class;
    }

    public List<Long> userRoles(long userId) {
        List<Long> roleIds = new ArrayList<>();
        List<UserWithRole> userWithRoles = userWithRoleDao.selectByUserId(userId);
        userWithRoles.forEach(userWithRole -> {
            roleIds.add(userWithRole.getRoleId());
        });
        return roleIds;
    }

    @Transactional
    public void updateUserRoles(long userId, List<Long> roleIds) {
        userWithRoleDao.deleteUserRole(userId);
        roleIds.forEach(roleId -> {
            UserWithRole userWithRole = new UserWithRole();
            userWithRole.setId(id.nextId());
            userWithRole.setRoleId(roleId);
            userWithRole.setUserId(userId);
            this.userWithRoleDao.insert(userWithRole);
        });
    }
}
